/*
 * CadastrarUsuario.java
 *
 * Created on 1 de Agosto de 2008, 20:29
 */

package gerenciadorprojetos.forms;

import gerenciadorprojetos.exception.UsuarioServiceException;
import gerenciadorprojetos.services.ProjetoService;
import gerenciadorprojetos.services.UsuarioService;
import java.awt.Color;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.jdesktop.application.Action;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author  eduardo
 */
public class CadastrarUsuario extends javax.swing.JDialog {

    /** Creates new form CadastrarUsuario */
    public CadastrarUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        inicializarFormulario();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelId = new javax.swing.JLabel();
        jLabelNome = new javax.swing.JLabel();
        jLabelSenha = new javax.swing.JLabel();
        jLabelEmail = new javax.swing.JLabel();
        jLabelApelido = new javax.swing.JLabel();
        jLabelResponsavel = new javax.swing.JLabel();
        jTextFieldID = new javax.swing.JTextField();
        jTextFieldNome = new javax.swing.JTextField();
        jPasswordFieldSenha = new javax.swing.JPasswordField();
        jTextFieldEmail = new javax.swing.JTextField();
        jTextFieldApelido = new javax.swing.JTextField();
        jComboBoxResponsavel = new javax.swing.JComboBox();
        jButtonInserir = new javax.swing.JButton();
        jButtonSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gerenciadorprojetos.GerenciadorProjetosApp.class).getContext().getResourceMap(CadastrarUsuario.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        jLabelId.setText(resourceMap.getString("jLabelId.text")); // NOI18N
        jLabelId.setName("jLabelId"); // NOI18N

        jLabelNome.setText(resourceMap.getString("jLabelNome.text")); // NOI18N
        jLabelNome.setName("jLabelNome"); // NOI18N

        jLabelSenha.setText(resourceMap.getString("jLabelSenha.text")); // NOI18N
        jLabelSenha.setName("jLabelSenha"); // NOI18N

        jLabelEmail.setText(resourceMap.getString("jLabelEmail.text")); // NOI18N
        jLabelEmail.setName("jLabelEmail"); // NOI18N

        jLabelApelido.setText(resourceMap.getString("jLabelApelido.text")); // NOI18N
        jLabelApelido.setName("jLabelApelido"); // NOI18N

        jLabelResponsavel.setText(resourceMap.getString("jLabelResponsavel.text")); // NOI18N
        jLabelResponsavel.setName("jLabelResponsavel"); // NOI18N

        jTextFieldID.setEditable(false);
        jTextFieldID.setText(resourceMap.getString("jTextFieldID.text")); // NOI18N
        jTextFieldID.setName("jTextFieldID"); // NOI18N

        jTextFieldNome.setText(resourceMap.getString("jTextFieldNome.text")); // NOI18N
        jTextFieldNome.setName("jTextFieldNome"); // NOI18N

        jPasswordFieldSenha.setText(resourceMap.getString("jPasswordFieldSenha.text")); // NOI18N
        jPasswordFieldSenha.setName("jPasswordFieldSenha"); // NOI18N

        jTextFieldEmail.setText(resourceMap.getString("jTextFieldEmail.text")); // NOI18N
        jTextFieldEmail.setName("jTextFieldEmail"); // NOI18N

        jTextFieldApelido.setText(resourceMap.getString("jTextFieldApelido.text")); // NOI18N
        jTextFieldApelido.setName("jTextFieldApelido"); // NOI18N

        jComboBoxResponsavel.setName("jComboBoxResponsavel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gerenciadorprojetos.GerenciadorProjetosApp.class).getContext().getActionMap(CadastrarUsuario.class, this);
        jButtonInserir.setAction(actionMap.get("InserirUsuario")); // NOI18N
        jButtonInserir.setName("jButtonInserir"); // NOI18N

        jButtonSair.setAction(actionMap.get("Sair")); // NOI18N
        jButtonSair.setName("jButtonSair"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabelResponsavel)
                            .addComponent(jLabelId)
                            .addComponent(jLabelEmail)
                            .addComponent(jLabelApelido)
                            .addComponent(jLabelSenha)
                            .addComponent(jLabelNome))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldNome, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                            .addComponent(jTextFieldID, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                            .addComponent(jPasswordFieldSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                            .addComponent(jTextFieldEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                            .addComponent(jTextFieldApelido, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                            .addComponent(jComboBoxResponsavel, 0, 638, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonInserir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSair)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelId)
                    .addComponent(jTextFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNome)
                    .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelSenha)
                    .addComponent(jPasswordFieldSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelEmail)
                    .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelApelido)
                    .addComponent(jTextFieldApelido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelResponsavel)
                    .addComponent(jComboBoxResponsavel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonInserir)
                    .addComponent(jButtonSair))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void inicializarFormulario() {
        context = new ClassPathXmlApplicationContext("spring-servlet.xml");
        pS = (ProjetoService)context.getBean("projetoService");
        uS = (UsuarioService)context.getBean("usuarioService");
        
        List<String> l = uS.getUsuarios();
        ListIterator<String> it = l.listIterator();
        while (it.hasNext()) 
            jComboBoxResponsavel.addItem(it.next());
        
        jComboBoxResponsavel.setSelectedItem(uS.getNomeUsuarioLogado());
        
        limparCampos();
    }
    
    public void limparCampos() {
        jLabelApelido.setForeground(Color.BLACK);
        jLabelEmail.setForeground(Color.BLACK);
        jLabelResponsavel.setForeground(Color.BLACK);
        jLabelNome.setForeground(Color.BLACK);
        jLabelSenha.setForeground(Color.BLACK);
        
        jTextFieldApelido.setText("");
        jTextFieldEmail.setText("");
        jTextFieldNome.setText("");
        jTextFieldID.setText("");
        jPasswordFieldSenha.setText("");
    }
    
    public boolean validaDados() {
        boolean ok = true;
        
        jLabelApelido.setForeground(Color.BLACK);
        jLabelEmail.setForeground(Color.BLACK);
        jLabelResponsavel.setForeground(Color.BLACK);
        jLabelNome.setForeground(Color.BLACK);
        jLabelSenha.setForeground(Color.BLACK);
        
        if ("".equals(jTextFieldNome.getText())) {
            jLabelNome.setForeground(Color.RED);
            ok = false;
        }
        
        if ("".equals(jTextFieldApelido.getText())) {
            jLabelApelido.setForeground(Color.RED);
            ok = false;
        }
        
        if ("".equals(jTextFieldEmail.getText())) {
            jLabelEmail.setForeground(Color.RED);
            ok = false;
        }

        return ok;
    }
    
    @Action
    public void InserirUsuario() {
        try {
            if (validaDados()) {
                jTextFieldID.setText(uS.addUsuario(jTextFieldNome.getText(), new String(jPasswordFieldSenha.getPassword()), jTextFieldEmail.getText(), jTextFieldApelido.getText(), (String) jComboBoxResponsavel.getSelectedItem()));
                JOptionPane.showMessageDialog(this, "Usuario foi cadastrado com sucesso !");
                limparCampos();
            }            
        } catch (UsuarioServiceException ex) {
            if (ex.getTipo() == UsuarioServiceException.APELIDO_JA_EXISTENTE) {
                logger.error("O apelido informado ja existe: "+ex.getMessage());
                jLabelApelido.setForeground(Color.RED);
            } else if (ex.getTipo() == UsuarioServiceException.RESPONSAVEL_INEXISTENTE) {
                logger.error("O responsavel informado nao existe: "+ex.getMessage());
                jLabelResponsavel.setForeground(Color.RED);
            } else if (ex.getTipo() == UsuarioServiceException.ERRO_CADASTRO_USUARIO) {
                logger.error("Ocorreu um erro no cadastro do usuario: "+ex.getMessage());
                JOptionPane.showMessageDialog(this, "Ocorreu em erro no cadastro do usuario. Favor contactar o analista responsavel !");
                Sair();
            } else {
                logger.error("Erro desconheciado ao cadastrar o usuario: "+ex.getMessage());
                JOptionPane.showMessageDialog(this, "Ocorreu em erro no cadastro do usuario. Favor contactar o analista responsavel !");
                Sair();
            }
            
        }
    }

    @Action
    public void Sair() {
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonInserir;
    private javax.swing.JButton jButtonSair;
    private javax.swing.JComboBox jComboBoxResponsavel;
    private javax.swing.JLabel jLabelApelido;
    private javax.swing.JLabel jLabelEmail;
    private javax.swing.JLabel jLabelId;
    private javax.swing.JLabel jLabelNome;
    private javax.swing.JLabel jLabelResponsavel;
    private javax.swing.JLabel jLabelSenha;
    private javax.swing.JPasswordField jPasswordFieldSenha;
    private javax.swing.JTextField jTextFieldApelido;
    private javax.swing.JTextField jTextFieldEmail;
    private javax.swing.JTextField jTextFieldID;
    private javax.swing.JTextField jTextFieldNome;
    // End of variables declaration//GEN-END:variables

    private ApplicationContext context;
    private ProjetoService pS;
    private UsuarioService uS;
    private Logger logger = Logger.getLogger(CadastrarUsuario.class);
    
}
